import { _decorator, Component, instantiate, Node, Prefab, ScrollView } from 'cc';
import { UIHeader } from '../common/UIHeader';
import { EventManager } from '../event/EventManager';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { Rank, RankOper } from '../entity/Rank';
import RankApi from '../api/RankApi';
import { PVPItem } from './PVPItem';
const { ccclass, property } = _decorator;

@ccclass('PVPList')
export class PVPList extends Component {
    @property(UIHeader)
    uiHeader:UIHeader
    @property(ScrollView)
    scrollView: ScrollView
    @property(Node)
    content:Node
    @property(Prefab)
    pvpItem:Prefab

    private page:number = 0
    private total:number = 0
    private size:number = 20

    start() {
        this.uiHeader.setData('英雄榜')
        EventManager.instance.on('英雄榜close', this.onClose, this)

        this.scrollView.node.on('scroll-to-top', () => {
            console.log('scroll-to-top....')
        }, this);
        this.scrollView.node.on('scroll-to-bottom', this.scrollToBottom, this);

        this.getList(1)
    }

    async getList(page) {
        this.page = page

        let params = {
            oper: RankOper.Hero,
            page: page
        }
        await UIManager.instance.showLoading()
        let res = await RankApi.Execute(params)
        UIManager.instance.closeLoading()
        let list = res.data.list
        this.total = res.data.total
        for (let i = 0; i< list.length; i++) {

            let node = instantiate(this.pvpItem)
            this.content.addChild(node)

            let rank = Rank.createByData(list[i])
            rank.Index = i+ 1 + (this.page - 1) * this.size
            node.getComponent(PVPItem).setData(rank)
        }
    }

    scrollToBottom(){
        if(this.page* this.size >= this.total){
            UIManager.instance.tip('没有更多了')
            return
        }

        this.page ++
        this.getList(this.page)
    }

    onClose(){
        UIManager.instance.closeUI(PrefabEnum.PVPList)
    }
}


